const axios = require('axios');

const API_BASE = 'http://localhost:3000/api';

async function testAPI() {
  console.log('🧪 开始测试API...');
  
  try {
    // 测试健康检查
    console.log('\n1. 测试健康检查...');
    const healthResponse = await axios.get(`${API_BASE.replace('/api', '')}/health`);
    console.log('✅ 健康检查成功:', healthResponse.data);
    
    // 测试获取歌曲列表
    console.log('\n2. 测试获取歌曲列表...');
    const songsResponse = await axios.get(`${API_BASE}/songs`);
    console.log('✅ 歌曲列表获取成功，共', songsResponse.data.songs.length, '首歌曲');
    
    // 查找目标歌曲
    const targetSongs = ['夜曲', '青花瓷', '七里香'];
    const foundSongs = songsResponse.data.songs.filter(song => 
      targetSongs.includes(song.name)
    );
    
    console.log('\n3. 查找目标歌曲...');
    if (foundSongs.length > 0) {
      console.log('✅ 找到目标歌曲:');
      foundSongs.forEach(song => {
        console.log(`   - ${song.name} (ID: ${song.id})`);
      });
      
      // 测试获取歌曲播放URL
      console.log('\n4. 测试获取歌曲播放URL...');
      for (const song of foundSongs) {
        try {
          const urlResponse = await axios.get(`${API_BASE}/songs/${song.id}/url`);
          console.log(`✅ ${song.name} 播放URL:`, urlResponse.data.url);
        } catch (error) {
          console.log(`❌ ${song.name} 获取播放URL失败:`, error.message);
        }
      }
    } else {
      console.log('❌ 未找到目标歌曲');
    }
    
    // 测试歌单
    console.log('\n5. 测试获取歌单...');
    const playlistsResponse = await axios.get(`${API_BASE}/playlists`);
    console.log('✅ 歌单获取成功，共', playlistsResponse.data.playlists.length, '个歌单');
    
    // 查找热门推荐歌单
    const hotPlaylist = playlistsResponse.data.playlists.find(p => p.name === '热门推荐');
    if (hotPlaylist) {
      console.log('✅ 找到热门推荐歌单，ID:', hotPlaylist.id);
      
      // 获取歌单详情
      const playlistDetailResponse = await axios.get(`${API_BASE}/playlists/${hotPlaylist.id}`);
      console.log('✅ 歌单详情获取成功，包含', playlistDetailResponse.data.songs.length, '首歌曲');
      
      // 检查是否包含目标歌曲
      const playlistSongs = playlistDetailResponse.data.songs;
      const targetSongsInPlaylist = playlistSongs.filter(song => 
        targetSongs.includes(song.name)
      );
      
      if (targetSongsInPlaylist.length > 0) {
        console.log('✅ 歌单中包含目标歌曲:');
        targetSongsInPlaylist.forEach(song => {
          console.log(`   - ${song.name} (ID: ${song.id})`);
        });
      } else {
        console.log('❌ 歌单中未找到目标歌曲');
      }
    }
    
    console.log('\n🎉 API测试完成！');
    
  } catch (error) {
    console.error('❌ API测试失败:', error.message);
    if (error.code === 'ECONNREFUSED') {
      console.log('💡 请确保后端服务器正在运行: node server-sqlite.js');
    }
  }
}

// 运行测试
testAPI();

